﻿using System;
using System.Linq;
using SqlSugar;
using SqlSugerexample.Model;

namespace SqlSugerexample.Models
{
    public class DatabaseContext
    {
        private static readonly Lazy<SqlSugarClient> _db = new Lazy<SqlSugarClient>(() =>
        {
            var db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = "Data Source=localhost;Initial Catalog=my_new_database;User ID=root;Password=wang.1995;",
                DbType = DbType.MySql,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true
            });

            // 映射模型到数据库表
            db.CodeFirst.InitTables(typeof(User));
            // 设置 SqlSugar 日志记录
            db.Aop.OnLogExecuted = (sql, pars) =>
            {
                Console.WriteLine(sql + "\r\n" +
                                  db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
            };
            db.Aop.OnError = (exp) => Console.WriteLine(exp.Message);
            return db;
        });

        public static SqlSugarClient Db => _db.Value;
    }
}
